package com.buer.service.impl;

import com.buer.dao.constants.BuerCostant;
import com.buer.dao.dmo.FingerPrintBG1Entity;
import com.buer.dao.enums.ResponseCodeEnum;
import com.buer.service.dto.BuerResult;
import com.buer.service.intf.FingerPrintGB1Service;
import com.buer.service.util.IoUtil;
import com.buer.service.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.buer.dao.enums.ResponseCodeEnum.SUCCESS;

/**
 * Created by buer on 2019/10/15.
 */
@Service
public class FingerPrintGB1ServiceImpl implements FingerPrintGB1Service {

    private static final Logger LOG = LoggerFactory.getLogger(FingerPrintGB1ServiceImpl.class);

    /**
     * 从文件中获取FingerPrintGB1配置信息
     */
    @Override
    public List<FingerPrintBG1Entity> obtainFingerPrintGB1FromConfFile() {
        List<FingerPrintBG1Entity> confs = new ArrayList<FingerPrintBG1Entity>();
        try {
            BufferedReader confBr = IoUtil.openFile(BuerCostant.FINGER_PRINT_GB1_FILE_PATH, BuerCostant.FINGER_PRINT_GB1_FILE_NAME);

            String line = confBr.readLine();
            while (line != null) {
                FingerPrintBG1Entity oneConf = obtainConfFromOneLine(line);
                if (null != oneConf) confs.add(oneConf);
                line = confBr.readLine();
            }
            confBr.close();

            return confs;
        } catch (IOException e) {
            LOG.error("获取FingerPrintGB1配置异常，e={}", e);
            return null;
        }
    }

    @Override
    public BuerResult saveConfStrToFile(String fingerPrintGB1Data) {
        BuerCostant.FINGERPRINT_GB1_DATA = fingerPrintGB1Data;
        List<String> confList = new ArrayList<String>();
        // 先检查
        String[] lines = fingerPrintGB1Data.split("\n");
        for (int index = 0; index < lines.length; index++) {
            String line = lines[index];
            if (StringUtils.isEmpty(line)) continue;
            BuerResult buerResult = checkOneLineConf(line);
            if (!SUCCESS.code.equals(buerResult.getResponseCode())) return buerResult;
            confList.add(line);
        }

        // 再保存
        IoUtil.createText(BuerCostant.FINGER_PRINT_GB1_FILE_PATH, BuerCostant.FINGER_PRINT_GB1_FILE_NAME, StringUtils.join(confList, "\n"));

        // 返回保存成功
        BuerResult successResult = new BuerResult();
        successResult.setResposeInfo(SUCCESS);
        return successResult;
    }

    @Override
    public String obtainConfFileStr() {
        // 1. 判断是否有配置文件文件夹，没有则创建
        File folder = new File(BuerCostant.FINGER_PRINT_GB1_FILE_PATH);
        if(!folder.exists()){
            folder.mkdirs();
            LOG.error("创建文件夹，path={}", BuerCostant.FINGER_PRINT_GB1_FILE_PATH);
        }

        // 2. 判断是否有文件，没有则创建默认的配置文件
        File file = new File(BuerCostant.FINGER_PRINT_GB1_FILE_PATH+BuerCostant.FINGER_PRINT_GB1_FILE_NAME);
        if (!file.exists()) {
            IoUtil.createText(BuerCostant.FINGER_PRINT_GB1_FILE_PATH, BuerCostant.FINGER_PRINT_GB1_FILE_NAME, BuerCostant.FINGERPRINT_GB1_DATA);

        }

        return IoUtil.readToString(BuerCostant.FINGER_PRINT_GB1_FILE_PATH, BuerCostant.FINGER_PRINT_GB1_FILE_NAME);
    }

    /**
     * 检查一条配置数据是否满足要求
     * 要求：用英文逗号分隔开，分开之后是两个数字
     *
     * @param oneLineconf
     * @return
     */
    @Override
    public BuerResult checkOneLineConf(String oneLineconf) {
        BuerResult buerResult = new BuerResult();
        String[] confCells = oneLineconf.split(",");
        if (confCells.length != 2) {
            buerResult.setResponseCode(ResponseCodeEnum.INPUT_ILLEGAL.code);
            buerResult.setResponseMsg(ResponseCodeEnum.INPUT_ILLEGAL.msg + oneLineconf);
            LOG.info(ResponseCodeEnum.INPUT_ILLEGAL.msg + oneLineconf + ",用逗号分隔开长度不是2");
            return buerResult;
        }

        for (int index = 0; index < confCells.length; index++) {
            String val = confCells[index];
            if (StringUtil.isNotNumber(val)) {
                buerResult.setResponseCode(ResponseCodeEnum.INPUT_ILLEGAL.code);
                buerResult.setResponseMsg(ResponseCodeEnum.INPUT_ILLEGAL.msg + oneLineconf);
                LOG.info(ResponseCodeEnum.INPUT_ILLEGAL.msg + oneLineconf + ",有非数字字符");
                return buerResult;
            }
        }

        buerResult.setResponseCode(SUCCESS.code);
        buerResult.setResponseMsg(SUCCESS.msg);
        return buerResult;
    }

    @Override
    public FingerPrintBG1Entity obtainConfFromOneLine(String oneLineconf) {
        BuerResult buerResult = checkOneLineConf(oneLineconf);
        if (!SUCCESS.code.equals(buerResult.getResponseCode())) {
            return null;
        }

        String[] splitStr = oneLineconf.split(",");
        FingerPrintBG1Entity entity = new FingerPrintBG1Entity();
        entity.setForce(Integer.valueOf(splitStr[0]));
        entity.setVelocity(Integer.valueOf(splitStr[1]));
        return entity;
    }
}
